/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dopdf.document.read;

import org.dopdf.document.model.PageDetail;
import org.dopdf.document.model.ResourceDetail;
import org.dopdf.document.hash.strategy.DocumentHashingStrategyDelegate;
import org.dopdf.io.ResponseWriter;

import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.logging.Logger;

/**
 * The class that will write the image data for a give pdf page on to the servlet output stream.
 *
 * @author Deep Shah
 */
public class PageWiseDocumentViewer {

    /**
     * The logger.
     */
    private final Logger logger = Logger.getLogger(PageWiseDocumentViewer.class.toString());

    /**
     * This method will lookout for the parameters like id of the document, document fetch strategy and
     * page number to render in the url.  Based on these values image of the chosen page will be rendered on the servlet
     * output stream.
     *
     * @param pageDetail the details about the page that is to be rendered.
     * @param response the servlet output stream.
     * @throws java.io.IOException in case if the we are unable to get the output stream from the response.
     */
    public void renderPage(final PageDetail pageDetail, final ServletResponse response) throws IOException {
        logger.fine("Geting the page: " + pageDetail.getPageNumber()
                + " for document with id: " + pageDetail.getDocumentId() + " using strategy: " +
                pageDetail.getDocumentFetchingStrategy());
        final DocumentReader documentReader = new DocumentHashingStrategyDelegate(
                pageDetail.getDocumentFetchingStrategy()).unHash(pageDetail.getDocumentId());
        final ResourceDetail resourceDetail = documentReader.getPageAsImage(pageDetail);
        new ResponseWriter(response).write(resourceDetail);

    }
}
